package com.lagou.rpc.provider.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Component;

/**
 * @author mcl
 * @date 2021/7/29 11:51 上午
 * @description
 */
@Slf4j
@Component
public class ZookeeperNode {

    public void createNode(String ip, int port) throws Exception {
        // 使用fluent编程风格
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("lg-rpc")  // 独立的命名空间 /base
                .build();

        client.start();

        log.info("会话创建了");

//        ip : port : lastResponseTime : lastResponseSpendTime
        String serverInfo = ip + ":" + port + ":0:0";

        // 创建
        String temp_path = "/server/"+port;
        String s1 = client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(temp_path, serverInfo.getBytes());

        log.info("成功注册服务器地址到注册中心: {}", s1);
    }
}
